import { useQuery } from '@tanstack/react-query';
import type { IPostFavourite } from '@/interfaces';
import { useContext } from 'react';
import { queryPostFavourites } from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Link from 'next/link';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { toRelativeTime } from '@/lib/tool';
import { UserIdPageContext } from '@/contexts/user-id';

export default function FavouritesUserIdH5Page() {
  const {
    source: { path, userDetails },
  } = useContext(UserIdPageContext)!;

  const queryPostFavouritesQuery = useQuery(
    ['/forum', '/posts', '/favourites'],
    async () => {
      return (await queryPostFavourites()) as IPostFavourite[];
    },
    {
      enabled: path.user?.id === userDetails.user.id,
    },
  );

  if (queryPostFavouritesQuery.data) {
    const posts = queryPostFavouritesQuery.data;

    return (
      <div>
        {posts.map((item) => {
          return (
            <div className="row" key={item.id}>
              <div className="col-12">
                <div className="yw-bg" style={{ height: '0.35rem' }}></div>
              </div>
              <div className="col-12 bg-white rounded-3 py-4">
                <div className="vstack gap-4 align-items-center">
                  <Name id={item.postId} name={item.name} />

                  <ReadMoreBtn id={item.id} createdBy={item.createdBy} />

                  <div className="card-footer text-secondary cursor-default">
                    <time dateTime={item.updatedOn}>
                      {toRelativeTime(item.updatedOn)}
                    </time>
                  </div>
                </div>
              </div>
            </div>
          );
        })}

        {posts.length === 0 && <Nodata />}
      </div>
    );
  }

  if (queryPostFavouritesQuery.error) {
    return <Alert message={queryPostFavouritesQuery.error} type="error" />;
  }

  return <AlertLoad />;
}

const Name = ({ id, name }: { id: number; name: string }) => {
  return (
    <div className="h4 fw-semibold mb-0">
      <div>
        <Link
          className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
          href={`/posts/${id}`}
        >
          {name}
        </Link>
      </div>
    </div>
  );
};

const ReadMoreBtn = ({
  id,
  createdBy,
}: {
  id: number;
  createdBy: number | undefined;
}) => {
  const {
    source: { path, userDetails },
    translatedFields,
  } = useContext(UserIdPageContext)!;

  return (
    <>
      {path.user?.id === createdBy ? (
        <Link className="btn btn-primary" href={`/posts/${id}/edit`}>
          <i className="bi bi-pencil-square me-2"></i>
          {translatedFields.editPost}
        </Link>
      ) : (
        <Link className="btn btn-primary" href={`/posts/${id}`}>
          {translatedFields.readMore}
        </Link>
      )}
    </>
  );
};
